#include <TFT_eSPI.h>
#include "Display.h"
#include "lvgl.h"

#include "demos/lv_demos.h"

TFT_eSPI tft = TFT_eSPI(); /* TFT instance */

static lv_disp_draw_buf_t  draw_buf;
static lv_color_t buf[ DISP_HOR_RES * DISP_VER_RES/2 ];

static void my_disp_flush(lv_disp_drv_t *disp, const lv_area_t *area, lv_color_t *color_p);

void Display_Init(void)
{
	tft.begin(); /* TFT init */
	tft.setRotation(0); /* Landscape orientation */
	tft.fillScreen(0xFFFF);
}
/**
  * @brief  显示初始化
  * @param  无
  * @retval 无
  */
void Lvgl_Init(void)
{
  lv_init();  // lvgl初始化

  tft.begin(); /* TFT init */
	tft.setRotation(0); /* Landscape orientation */
	tft.fillScreen(0xFFFF);

  lv_disp_draw_buf_init(&draw_buf, buf, NULL,  DISP_HOR_RES * DISP_VER_RES/2 );  // LVGL 初始化

  /*Initialize the display*/
  static lv_disp_drv_t disp_drv;  // 实现将渲染图像复制到显示区域
  lv_disp_drv_init(&disp_drv);
  disp_drv.hor_res = DISP_HOR_RES;
  disp_drv.ver_res = DISP_VER_RES;
  disp_drv.flush_cb = my_disp_flush;
  disp_drv.draw_buf = &draw_buf;
  lv_disp_drv_register(&disp_drv);

  //lv_demo_widgets();
  //lv_demo_benchmark();
}

/**
  * @brief  屏幕全局刷新函数
  * @param  无
  * @retval 无
  */
static void my_disp_flush(lv_disp_drv_t *disp, const lv_area_t *area, lv_color_t *color_p)
{
  int32_t w = (area->x2 - area->x1 + 1);
  int32_t h = (area->y2 - area->y1 + 1);

  tft.startWrite();

  #if DISP_ROTATE == 0
    tft.setAddrWindow(area->x1, area->y1, w, h);
  #elif DISP_ROTATE == 1
    tft.setAddrWindow(area->x1 + 20, area->y1, w, h);
  #endif

  tft.pushColors((uint16_t *)(&color_p->full), w * h, true);
  tft.endWrite();

  lv_disp_flush_ready(disp);
}
/**
  * @brief  屏幕全局刷新测试函数
  * @param  无
  * @retval 无
  */
static void Screen_Test(void)
{
    tft.init();

    int startTime = micros();

    tft.fillScreen(TFT_RED);
    tft.fillScreen(TFT_GREEN);
    tft.fillScreen(TFT_BLUE);

    int drawTime = micros() - startTime;

    Serial.begin(115200);
    Serial.println("Hello from ESP-IDF!");
    Serial.print("Draw time was: ");
    Serial.print(drawTime);
    Serial.println(" microseconds.");
    while(1) {
        delay(1);
    }
}
